/*
 * 
 * 
 * 
 */
package com.cms.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;

import com.alibaba.fastjson.JSONObject;
import com.cms.Feedback;
import com.cms.entity.Form;
import com.cms.entity.Model;
import com.cms.entity.ModelField;
import com.cms.routes.RouteMapping;


/**
 * Controller - 表单
 * 
 * 
 * 
 */
@RouteMapping(url = "/admin/form")

public class FormController extends BaseController {

	/**
	 * 编辑
	 */
	public void edit() {
		Long id = getParaToLong("id");
		Form form = new Form().dao().findById(id);
		List<ModelField> modelFields = new ModelField().dao().findList(form.getModelId(), null,getCurrentSite().getId());
		setAttr("modelFields",modelFields);
		setAttr("form", new Form().dao().findById(id));
		render(getView("form/edit"));
	}

	/**
	 * 更新
	 */
	public void update() {
		Long id = getParaToLong("id");
		Form form = new Form().dao().findById(id);
		List<ModelField> modelFields = new ModelField().dao().findList(form.getModelId(), null,getCurrentSite().getId());
		Map<String,Object> model = new HashMap<String,Object>();
		for(ModelField modelField : modelFields){
			String value = getPara(modelField.getName());
			model.put(modelField.getName(), value);
		}
		form.setSiteId(getCurrentSite().getId());
		form.setModifyDate(new Date());
		form.setModelFieldValue(JSONObject.toJSONString(model));
		form.update();
		redirect(getListQuery("/admin/form/data?modelId="+form.getModelId()));
	}

   /**
     * 列表
     */
    public void list(){
        setAttr("models", new Model().dao().findList(Model.FORM_TYPE,getCurrentSite().getId()));
        render(getView("form/list"));
    }
	
	/**
	 * 列表
	 */
	public void data() {
		Long modelId = getParaToLong("modelId");
		Integer pageNumber = getParaToInt("pageNumber");
		if(pageNumber==null){
			pageNumber = 1;
		}
		List<ModelField> modelFields = new ModelField().dao().findList(modelId, true,getCurrentSite().getId());
		setAttr("modelFields",modelFields);
		setAttr("page", new Form().dao().findPage(modelId,null,pageNumber,PAGE_SIZE,getCurrentSite().getId()));
		render(getView("form/data"));
	}

	/**
	 * 删除
	 */
	public void delete() {
		Long ids[] = getParaValuesToLong("ids");
		if(ArrayUtils.isNotEmpty(ids)){
			for(Long id:ids){
				new Form().dao().deleteById(id);
			}
		}
		renderJson(Feedback.success(new HashMap<>()));
	}

}